import axios         from 'axios'
import { Loading }   from 'element-ui';
import {DEVPATH} from '@/common/js/constant'
import {get_Token,get_Userinfo,get_TokenML} from '@/utils/auth.js'
//post
export function post(url, params={}, success, err) {
  let token = get_Token();
  let loadingInstance = Loading.service({lock: true,});
  let thar = this;
  // 请求时的拦截
  var dev = DEVPATH;
  axios.interceptors.request.use(function(config) {
    if(token != null ){//有token 把头传过去
     config.headers.sys_token = token;
     config.headers.token = get_TokenML();
    }
    return config;
  }, function(error) {
    return Promise.reject(error);
  });
  axios.post(dev + url, params)
    .then(function(res) {
       console.log(res);
        res = res.data;
      switch(res.code)
      {
        case 100:
             success(res.data || res.msgg);
             loadingInstance.close();
            break;
        case 103:
             loadingInstance.close();
             success(res.code);
            break;
        case 400 || get_Userinfo() == null:
          loadingInstance.close();
            thar.$router.push({ path: '/login' })
            break;
        default:
          loadingInstance.close();
          err(res.msg);
      }
    })
    .catch(function(error) {
      err('网络错误，数据暂时无法获取，请稍后重试');
      loadingInstance.close();
    });
}
//delete
export function dele(url, params, success, err, method) {
    axios.post(dev + url, params)
        .then(function(res) {
            res = res.data;
            if (res.code == 100) {
                success(res || res.msg);
            } else {
                err(res.msg);
            }
        })
        .catch(function(error) {
            err('网络错误', error)
        });
};
//patch
export function patch(url, data) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(reponse.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}
//put  更新
export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function get(url, params = {}) {
  var dev = DEVPATH;
  axios.get(dev + url, params)
      .then(function(res) {
          res = res.data;
          if (res.code == 100) {
              success(res || res.msg);
          } else {
              err(res.msg);
          }
      })
      .catch(function(error) {
          err('网络错误', error)
      });
}
